package com.example.dell.fastshopping.user.task;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.dell.fastshopping.MyApplication;
import com.example.dell.fastshopping.R;
import com.example.dell.fastshopping.network.ApiService;
import com.example.dell.fastshopping.network.NetCallback;
import com.example.dell.fastshopping.network.RetrofitClient;
import com.example.dell.fastshopping.network.http.BaseResponse;
import com.example.dell.fastshopping.user.modle.TaskActivityViewMolde;
import com.example.dell.fastshopping.utils.DensityUtil;
import com.example.dell.fastshopping.utils.ToastUtils;
import com.example.dell.fastshopping.utils.ZxingUtils;
import com.example.dell.fastshopping.wxapi.WXEntryActivity;
import com.google.gson.GsonBuilder;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class TaskActivity extends AppCompatActivity implements IUiListener {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.my_invite_code)
    TextView myInviteCode;
    @BindView(R.id.link)
    TextView link;
    @BindView(R.id.weixin_num)
    TextView weixinNum;
    @BindView(R.id.lin_weixin)
    TextView linWeixin;

    @BindView(R.id.qq_num)
    TextView qqNum;
    @BindView(R.id.lin_qq)
    TextView linQq;

    @BindView(R.id.wx_public_num)
    TextView wxPublicNum;
    @BindView(R.id.lin_weixin_public)
    TextView linWeixinPublic;

    @BindView(R.id.share_num)
    TextView shareNum;
    @BindView(R.id.share_2_wxfriends)
    TextView share2Wxfriends;
    @BindView(R.id.invite_regist_num)
    TextView inviteRegistNum;
    @BindView(R.id.invite_regist)
    TextView inviteRegist;
    @BindView(R.id.qrcode)
    ImageView qrcode;
    @BindView(R.id.right_text)
    TextView rightText;
    private TaskActivityViewMolde molde;
    private TaskType mTaskType;
    private SharePopuWindow popuWindow;
    private int taskID;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task);
        ButterKnife.bind(this);
        molde = ViewModelProviders.of(this).get(TaskActivityViewMolde.class);
        initView();
    }

    private void initView() {
        title.setText("任务");
        rightText.setVisibility(View.VISIBLE);
        rightText.setText("邀请记录");

        popuWindow = new SharePopuWindow(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.share_weixin:
                        share2Wxfriends(0);
                        break;
                    case R.id.share_weixin_group:
                        share2Wxfriends(1);
                        break;
                    case R.id.share_qq:
                      //  shareToQQ();
                        break;
                    case R.id.share_qq_group:
                       // shareToQZone();
                        break;
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        molde.getTaskList().observe(this, new Observer<TaskType>() {
            @Override
            public void onChanged(@Nullable TaskType tasktype) {
                //1,1,1,10,1
//                KLog.e(new GsonBuilder().create().toJson(tasktype));
                mTaskType = tasktype;
                taskID = tasktype.getId();
                WXEntryActivity.setTaskID(taskID);//分享成功回调后，需要掉接口传id;
                int weixinGourp = tasktype.getWeixinGourp();
                weixinNum.setText(weixinGourp == -1 ? "1" : weixinGourp + "");

                int status = 0;
                if (weixinGourp == -1) {
                    status = -1;
                } else if (weixinGourp >= 1) {
                    status = 1;
                } else {
                    status = 0;
                }
                initButton(linWeixin, status);

                int qqGourp = tasktype.getQqGourp();
                qqNum.setText(qqGourp == -1 ? "1" : qqGourp + "");
                if (qqGourp == -1) {
                    status = -1;
                } else if (qqGourp >= 1) {
                    status = 1;
                } else {
                    status = 0;
                }
                initButton(linQq, status);

                int gzh = tasktype.getWeixinGzh();
                wxPublicNum.setText(gzh == -1 ? "1" : gzh + "");
                if (gzh == -1) {
                    status = -1;
                } else if (gzh >= 1) {
                    status = 1;
                } else {
                    status = 0;
                }
                initButton(linWeixinPublic, status);

                int weixinShare = tasktype.getWeixinShare();
                shareNum.setText(weixinShare == -1 ? "10" : weixinShare + "");
                if (weixinShare == -1) {
                    status = -1;
                } else if (weixinShare >= 10) {
                    status = 1;
                } else {
                    status = 0;
                }
                initButton(share2Wxfriends, status);

                int invitationRegister = tasktype.getInvitationRegister();
                inviteRegistNum.setText(invitationRegister == -1 ? "1" : invitationRegister + "");
                if (invitationRegister == -1) {
                    status = -1;
                } else if (invitationRegister >= 1) {
                    status = 1;
                } else {
                    status = 0;
                }

                initButton(inviteRegist, status);
                link.setText(tasktype.getUrl() + "");
                myInviteCode.setText("您的邀请码：" + tasktype.getInvitationCode());
                String url = tasktype.getUrl();
                //判断URL合法性
                if (url == null || "".equals(url) || url.length() < 1) {
                    ToastUtils.showShort("二维码为空");
                    return;
                }
                int px = DensityUtil.dp2px(TaskActivity.this, 184);
                Bitmap bitmap = ZxingUtils.createBitmap(url, px, px);
                Glide.with(TaskActivity.this).load(bitmap)
                        .error(R.mipmap.default_user_icon) //异常时候显示的图片
                        .placeholder(R.mipmap.default_user_icon) //加载成功前显示的图片...
                        .into(qrcode);
            }
        });
    }

    /**
     * @param button
     * @param status -1 已领取积分；0，待完成； 1 领积分
     */
    private void initButton(TextView button, int status) {
        int white = TaskActivity.this.getResources().getColor(R.color.white);
        int myred = TaskActivity.this.getResources().getColor(R.color.myRed);
        if (status == 0) {
            button.setText("去完成");
            button.setTextColor(white);
            button.setBackgroundResource(R.drawable.red_button);
            button.setTag(false);
        } else if (status == 1) {
            button.setText("领积分");
            button.setTextColor(myred);
            button.setBackgroundResource(R.drawable.red_empty_buttom);
            button.setTag(true);
        } else {
            button.setText("已领取");
            button.setTextColor(white);
            button.setBackgroundResource(R.drawable.gray_circle_buttom);
            button.setTag(true);
        }
    }

    //1.消耗/2.提现/3.加价/4.返利/5.竞拍轮次积分/6.竞拍得主积分/7.奖励/8.邀请qq群任务/
//            9.邀请微信群任务/10.邀请微信公众号任务/11.微信分享任务/12.邀请注册任务
    @OnClick({R.id.back, R.id.right_text,
            R.id.lin_weixin, R.id.lin_qq, R.id.lin_weixin_public, R.id.share_2_wxfriends, R.id.invite_regist})
    public void onClick(View view) {
        boolean tag = false;
        if (view.getId() != R.id.back && view.getId() != R.id.right_text)
            tag = (boolean) view.getTag();
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.lin_weixin:
                if (tag) {
                    linqu(9);
                } else {
                    toJionPage(2);
                }
                break;
            case R.id.lin_qq:
                if (tag) {
                    linqu(8);
                } else {
                    toJionPage(1);
                }

                break;
            case R.id.lin_weixin_public:
                if (tag) {
                    linqu(10);
                } else {
                    toJionPage(3);
                }
                break;
            case R.id.share_2_wxfriends:
                if (tag) {
                    linqu(11);
                } else {
                    popuWindow.showAtLocation(TaskActivity.this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
                }

                break;
            case R.id.invite_regist:
                if (tag) {
                    linqu(12);
                } else {
                    //TODO:
                }

                break;

            case R.id.right_text:
                toInviteRecorde();
                break;
        }
    }

    private void toInviteRecorde() {
        Intent intent = new Intent(this, InviteRecordActivity.class);
        startActivity(intent);
    }

    private void share2Wxfriends(int type) {

        //初始化一个 WXTextObject 对象，填写分享的文本内容
        WXTextObject textObj = new WXTextObject();
        textObj.text = "拍我所“拍“  赏我所“赏”  让艺术生活触手可及！";

        //用 WXTextObject 对象初始化一个 WXMediaMessage 对象
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObj;
//        msg.description = text;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = buildTransaction("text");
        req.message = msg;
        if (type == 0) {
            req.scene = SendMessageToWX.Req.WXSceneSession;//朋友
        } else {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        //调用api接口，发送数据到微信
        IWXAPI api = MyApplication.getWxAPI();
        api.sendReq(req);
    }

    //type: 1:qq群 2:微信群 3:公众号
    private void toJionPage(int type) {
        Intent intent = new Intent(this, JoinPageActivity.class);
        intent.putExtra("type", type);
        startActivity(intent);
    }

    private void linqu(int type) {
        molde.getTaskIntegral(type, mTaskType.getId()).observe(this, new Observer<BaseResponse>() {
            @Override
            public void onChanged(@Nullable BaseResponse response) {
                if (response.isSuccess()) {
                    ToastUtils.showShort("领取成功");
                    initData();
                }
            }
        });
    }

    private void shareToQQ() {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "小牛竞拍");// 标题
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "拍我所“拍“  赏我所“赏”  让艺术生活触手可及！");// 摘要
        Tencent mTencent = MyApplication.getQQAPI();
        mTencent.shareToQQ(TaskActivity.this, params, this);
    }


    private void shareToQZone() {
        Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, "小牛竞拍");// 标题
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, "拍我所“拍“  赏我所“赏”  让艺术生活触手可及！");// 摘要
        Tencent mTencent = MyApplication.getQQAPI();
        mTencent.shareToQzone(TaskActivity
                .this, params, this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Tencent mTencent = MyApplication.getQQAPI();
        mTencent.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, this);

    }

    @Override
    public void onComplete(Object o) {
        molde.share(taskID);
    }

    @Override
    public void onError(UiError uiError) {
        ToastUtils.showShort(uiError.errorMessage);
    }

    @Override
    public void onCancel() {
        ToastUtils.showShort("取消");
    }
}


